package com.lian.chatroom.server.handler;

import com.lian.chatroom.message.GroupCreateRequestMessage;
import com.lian.chatroom.message.GroupCreateResponseMessage;
import com.lian.chatroom.server.session.Group;
import com.lian.chatroom.server.session.GroupSession;
import com.lian.chatroom.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * 创建群聊处理器
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        //获取组名和成员
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        //创建群组
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        //如果创建的组名不存在，就创建成功
        if (group != null){
            //发送成功消息
            ctx.writeAndFlush(new GroupCreateResponseMessage(true,groupName + "创建成功"));
            // 发送拉群消息,根据群组名获取群成员的通道
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true,"您已被拉入 " + groupName));
            }
        }else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,groupName + "已经存在"));
        }
    }
}
